package com.iflytek.uoamp.agent.monitor.lib;

import java.io.UnsupportedEncodingException;
import java.nio.ByteBuffer;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;

import org.apache.log4j.Logger;

import com.iflytek.uoamp.agent.core.sender.monitorsender.monitorinterface.IItem;
import com.iflytek.uoamp.agent.core.sender.monitorsender.responseObj.ThriftFlumeEvent;


public class LibSendObj implements IItem {

	private ThriftFlumeEvent event = new ThriftFlumeEvent();

	public LibSendObj(ThriftFlumeEvent event) {
		this.event = event;
	}
	
	public LibSendObj(Map<String,String> headers,ByteBuffer body) {
		this.event = new ThriftFlumeEvent(headers,body);
	}
	
	public LibSendObj(Map<String,String> headers,byte[] body) {
		this.event = new ThriftFlumeEvent(headers,ByteBuffer.wrap(body));
	}

	public ThriftFlumeEvent getEvent() {
		return event;
	}

	public void setEvent(ThriftFlumeEvent event) {
		this.event = event;
	}

	/**
	 * change map to string ,and replace especial char
	 * @param request
	 * @return
	 */
	public String mapToString(Map<String, String> request){
		StringBuffer result = new StringBuffer();
		Iterator<Entry<String, String>> it = request.entrySet().iterator();
		while(it.hasNext()){
			Entry<String, String> entry = it.next();
			result.append(entry.getKey());
			result.append((char)31);
			String temp = entry.getValue().replaceAll("\n", "5>//n<7");
			temp = temp.replaceAll("\r", "5>//r<7");
			result.append(temp);
			result.append((char)31);
		}
		return result.toString();
	}
	
	@Override
	public String caseToString() {
		String body;
		try {
			body = new String(event.exchangeBodyToByte(),"utf-8");
		} catch (UnsupportedEncodingException e) {
			Logger.getRootLogger().error(e.getMessage(),e);
			body = new String(event.exchangeBodyToByte());
		}
		body = body.replaceAll("\n", "5>//n<7");
		body = body.replaceAll("\r", "5>//r<7");
		String header = mapToString(event.getHeaders());
		return header+(char)31+(char)32+(char)31+body;
	}

	@Override
	public String getSendPath() {
		return "append";
	}

	@Override
	public String getSendListPath() {
		return "appendbatch";
	}

}
